package main.java;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    // 简单的用户验证（实际应用中应从数据库验证）
    private boolean isValidUser(String username, String password) {
        return "admin".equals(username) && "password123".equals(password);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (isValidUser(username, password)) {
            // 创建会话并设置用户属性
            HttpSession session = request.getSession();
            session.setAttribute("user", username);

            // 重定向到欢迎页面
            response.sendRedirect("welcome.jsp");
        } else {
            // 重定向回登录页面并显示错误
            response.sendRedirect("login.jsp?error=1");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 如果是GET请求，重定向到登录页面
        response.sendRedirect("login.jsp");
    }
}